import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:peach/config/_.dart';
import 'package:peach/entity/_.dart';
import 'package:peach/utils/_.dart';
import 'package:peach/service/_.dart';
import 'package:peach/event/_.dart';
import 'package:peach/views/Home/Default.dart';
import 'package:peach/views/Home/ClassList.dart';
import 'package:peach/views/Home/Random.dart';

/*
 * 首页
 */
class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _Home();
}

class _Home extends State<Home> with AutomaticKeepAliveClientMixin<Home> {

  /// 保存横向菜单的数据
  ClassResult Tabs = ClassResult.fromJson({
    'principal': [], 'additional': []
  });

  int _currentIndex = 0;

  @override
  bool get wantKeepAlive => true;

  TabController _tabController;
  @override
  void initState() {
    super.initState();
    /// 请求权限
    AuthorityApplication.init(context);
    _GetClassData();
    _EditOnListen();
  }

  void _EditOnListen () {
    Config.eventBus.on<ClassEditEvent>().listen((event){
      print("事件监听 ClassEditEvent ============== ：${event.update}");
      if (event.update) {
        print("true");
        _currentIndex = 0;
        Tabs = ClassResult.fromJson({ 'principal': [], 'additional': [] });
        _GetClassData();
      } else {
        print("false");
      }
    });
  }

  void _GetClassData() async {
    if (Tabs.principal.length == 0) {
      Tabs = await HomeService.GetClassData(params: {});
      // 插入首页
      Tabs.principal.insert(0, Principal.fromJson({ 'id': 0, 'title': '随机展示','page': 0, }));
      Tabs.principal.insert(0, Principal.fromJson({ 'id': 1, 'title': '首页','page': 0,}));
      setState(() {});
    }
  }

  /// 横向滑动分类菜单边上的右侧编辑按钮
  Widget RightEdit() {
    return Container(
      width: Screen.setWidth(50),
      child: IconButton(
          iconSize: Screen.setFontSize(20.0),
          icon: const Icon(Icons.edit, color: ColorConfig.NoActiveColor,),
          onPressed: () {
            Modular.to.pushNamed('/edit');
          }
      ),
    );
  }

  /// 横向滑动分类菜单
  Widget MenuList() {
    return Expanded(
      child: TabBar(
        isScrollable: true,
        unselectedLabelColor: ColorConfig.NoActiveColor,
        indicatorColor: ColorConfig.ThemeColor,
        tabs: Tabs.principal.map((e) => Tab(text: e.title,)).toList(),
        onTap: (int index) {
          print("你点击的下标为 ============== ：$index");
        },
      ),
    );
  }

  /// 左侧Logo按钮
  Widget Leading () {
    return Builder(
      builder: (BuildContext context) {
        return IconButton(
          icon: IconFont.LogoIcon(),
          onPressed: () {

          }
        );
      },
    );
  }

  /// 标题的容器
  Widget TitleWidget() {
    return InkWell(
      onTap: () {
        Modular.to.pushNamed("/search");
      },
      child: Container(
        height: Screen.setHeight(30.0),
        alignment: Alignment.center,
        width: double.infinity,
        decoration: BoxDecoration(
          color: ColorConfig.WhiteBackColor,
          borderRadius: BorderRadius.all(Radius.circular(25.0)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(Icons.search, color: Color(0XFF999999), size: 14),
            SizedBox(width: Screen.setWidth(2.0)),
            Text("198万张图，有你想要的...", style: TextStyle(color: Color(0xFf999999), fontSize: Screen.setFontSize(13)))
          ],
        ),
      ),
    );
  }

  /// 返回不同的布局
  List<Widget> TabView() {
    return Tabs.principal.map((e) =>
    e.id == 1
        ? DefaultLayout()
        : e.id == 0 ? Random() : ClassList(id: e.id,key: GlobalKey(),)
    ).toList();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return DefaultTabController(
      key: GlobalKey(),
      length: Tabs.principal.length != 0 ? Tabs.principal.length : 0,
      initialIndex: _currentIndex,
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(90.0),
          child: AppBar(
            primary: true,
            titleSpacing: 0.0,
            backgroundColor: ColorConfig.ThemeColor,
            leading: Leading(),
            title: TitleWidget(),
            elevation: 0,
            actions: [
              IconButton(
                iconSize: 24,
                icon: Icon(Icons.supervisor_account),
                onPressed: () {
                  Config.tabController.jumpToPage(3);
                },
              )
            ],
            bottom: PreferredSize(
              preferredSize: Size.fromHeight(40.0),
              child: Row(
                children: [
                  MenuList(),
                  RightEdit()
                ],
              )
            ),
          ),
        ),
        body: TabBarView(
          children: TabView()
        ),
      ),
    );
  }
}
